from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.modules.bank_card import BankCard
from comment.modules.user import User
from comment.utils.decorators import login_required
from comment.modules import db
from financial.resources.card.serializer import BankCardListSerializer

class Card_Resource(Resource):
    '''
    银行卡 管理的资源类
    '''
    method_decorators = [login_required]
    def post(self):
        uid = g.user_id
        login_user =User.query.filter(User.id==uid).first()

        rp = RequestParser()
        rp.add_argument('holder',required=True) #账号的名字
        rp.add_argument('openingBank',required=True) #开户银行
        rp.add_argument('bankBranch',required=True) #支行
        rp.add_argument('cityId',required=True) #城市id
        rp.add_argument('cardNum',required=True) #卡片号码

        args = rp.parse_args()

        holder = args.holder
        opening_bank = args.openingBank
        bank_branch = args.bankBranch
        city_id = args.cityId
        bank_card_num = args.cardNum


        #验证银行卡是否唯一
        card_info = BankCard.query.filter(BankCard.bankCardNum == bank_card_num).first()
        if card_info:
            return {'message':'银行卡已经存在，请勿重复添加','code':20001}

        #
        card = BankCard(openingBank=opening_bank,bankCardNum=bank_card_num,bankBranch=bank_branch,cityId=city_id,holder=holder,userId=uid,reservePhone=login_user.phone)
        db.session.add(card)
        db.session.commit()
        return {'msg':'success'}


    def get(self):
        '''
        查询当前登录用户所拥有的银行卡列表
        :return:
        '''
        uid= g.user_id

        #查询数据库中  当前用户所拥有的银行卡
        card_list = BankCard.query.filter(BankCard.userId==uid).all()
        if card_list:#把对象装换成字典数据
            return BankCardListSerializer(card_list).to_dict()
        else:
            return {}
